<?php


//赞模块路由

Route::get('/posts/{post}/zan','ZanController@zan');
Route::get('/posts/{post}/unzan','ZanController@unzan');


//Post模型中文章是否被点赞，被谁点赞
public function zan($user_id)
{
    return $this->hasOne('App\Zan')->where('user_id',$user_id);
}
//文章拥有的所有赞
public function zans(){
    return $this->hasMany('App\Zan');
}

//逻辑方法
class ZanController extends Controller
{
    public function zan(Post $post){
        $data = [
            'user_id'=>Auth::id(),
            'post_id'=>$post->id
        ];
        Zan::firstOrCreate($data); //如果有就查询，没有就创建
        return back();
    }

    public function unzan(Post $post){

        $post->zan(Auth::id())->delete();

        return back();
    }
}

//视图
@if($post->zan(\Illuminate\Support\Facades\Auth::id())->exists())
        <a href="/posts/{{ $post->id }}/unzan" type="button" class="btn btn-primary">取消赞</a>
    @else
    <a href="/posts/{{ $post->id }}/zan" type="button" class="btn btn-primary">赞</a>
    @endif
